export function imgLazy() {
  const imgs = document.querySelectorAll('img');
  const context = document.querySelector('.content');
  // offsetTop是元素与offsetParent的距离，循环获取直到页面顶部
  function getTop(e) {
    let T = e.offsetTop;
    // eslint-disable-next-line no-param-reassign
    while ((e = e.offsetParent)) {
      T += e.offsetTop;
    }
    return T;
  }

  function lazyLoad(imgs) {
    let H = context.clientHeight; // 获取可视区域高度
    let S = context.scrollTop;
    for (let i = 0; i < imgs.length; i++) {
      const dataSrc = imgs[i].getAttribute('data-src');
      if (H + S >= getTop(imgs[i]) && dataSrc) {
        imgs[i].src = imgs[i].getAttribute('data-src');
      }
    }
  }
  window.onload = lazyLoad(imgs);
  context.onscroll = function () {
    // onscroll()在滚动条滚动的时候触发
    lazyLoad(imgs);
  };
}
